package com.mapaoer.payment.service.impl;

import com.mapaoer.payment.entity.MembershipRecharge;
import com.mapaoer.payment.entity.MembershipType;
import com.mapaoer.payment.repository.MembershipRechargeRepository;
import com.mapaoer.payment.repository.MembershipTypeRepository;
import com.mapaoer.payment.feign.UserServiceFeignClient;
import com.mapaoer.payment.service.MembershipService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

import jakarta.persistence.*;


@Service
@RequiredArgsConstructor
public class MembershipServiceImpl implements MembershipService {

    private final MembershipTypeRepository membershipTypeRepository;
    private final MembershipRechargeRepository rechargeRepository;
    private final UserServiceFeignClient userServiceFeignClient;


    @Override
    public List<MembershipType> getEnabledMembershipTypes() {
        return membershipTypeRepository.findByEnabledTrue();
    }

    @Override
    @Transactional
    public MembershipRecharge createRechargeOrder(Long userId, Long membershipTypeId, MembershipRecharge.PaymentMethod paymentMethod) {
        // 验证会员类型存在且已启用
        MembershipType membershipType = membershipTypeRepository.findById(membershipTypeId)
                .orElseThrow(() -> new IllegalArgumentException("会员类型不存在"));
        if (!membershipType.getEnabled()) {
            throw new IllegalArgumentException("会员类型已关闭");
        }

        // 创建充值订单
        MembershipRecharge recharge = new MembershipRecharge();
        recharge.setUserId(userId);
        recharge.setMembershipTypeId(membershipTypeId);
        recharge.setAmount(membershipType.getPrice());
        recharge.setPaymentMethod(paymentMethod);
        recharge.setStatus(MembershipRecharge.RechargeStatus.PENDING);
        recharge.setTransactionId(generateTransactionId());

        return rechargeRepository.save(recharge);
    }

    @Override
    @Transactional
    public MembershipType updateMembershipTypeStatus(Long typeId, boolean enabled) {
        MembershipType membershipType = membershipTypeRepository.findById(typeId)
                .orElseThrow(() -> new IllegalArgumentException("会员类型不存在"));
        membershipType.setEnabled(enabled);
        return membershipTypeRepository.save(membershipType);
    }

    @Override
    public List<MembershipRecharge> getUserRechargeRecords(Long userId, MembershipRecharge.RechargeStatus status) {
        if (status == null) {
            return rechargeRepository.findByUserIdOrderByCreateTimeDesc(userId);
        } else {
            return rechargeRepository.findByUserIdAndStatusOrderByCreateTimeDesc(userId, status);
        }
    }

    @Override
    @Transactional
    public String handlePaymentCallback(String paymentMethod, Map<String, String> callbackParams) {
        // 实际项目中需验证回调签名
        String transactionId = callbackParams.get("out_trade_no");
        String tradeStatus = callbackParams.get("trade_status");

        MembershipRecharge recharge = rechargeRepository.findByTransactionId(transactionId)
                .orElseThrow(() -> new IllegalArgumentException("订单不存在"));

        if ("SUCCESS".equals(tradeStatus)) {
            recharge.setStatus(MembershipRecharge.RechargeStatus.COMPLETED);
            recharge.setPaymentGatewayResponse(callbackParams.toString());
            rechargeRepository.save(recharge);
            // 调用用户服务更新会员有效期
            LocalDateTime now = LocalDateTime.now();
            MembershipType membershipType = membershipTypeRepository.findById(recharge.getMembershipTypeId())
                .orElseThrow(() -> new IllegalArgumentException("会员类型不存在"));
            LocalDateTime endTime = now.plusDays(membershipType.getDays());
            userServiceFeignClient.updateMembershipExpiry(recharge.getUserId(), 
                Date.from(now.atZone(ZoneId.systemDefault()).toInstant()),
                Date.from(endTime.atZone(ZoneId.systemDefault()).toInstant()));
            return "success";
        } else {
            recharge.setStatus(MembershipRecharge.RechargeStatus.FAILED);
            rechargeRepository.save(recharge);
            return "fail";
        }
    }

    private String generateTransactionId() {
        return "MEMBER" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 8);
    }
}